package com.iexbuy.ihg.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.navisdk.util.common.StringUtils;
import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.Shop;
import com.iexbuy.ihg.entity.ShopItemDetailObject;
import com.iexbuy.ihg.entity.ShopItemListObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ShopDetailFragment extends BaseFragment {

	private static ShopDetailFragment homeFragmentInstent;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListRefreshLayout;
	@ViewInject(R.id.listView)
	private ListView listView;

	private LinearLayout listHeaderView;
	@ViewInject(R.id.shopIcon)
	private ImageView shopIcon;
	@ViewInject(R.id.shopTitle)
	private TextView shopTitle;

	@ViewInject(R.id.shopDistance)
	private TextView shopDistance;
	@ViewInject(R.id.shopAddress)
	private TextView shopAddress;
	@ViewInject(R.id.shopTitleIcon)
	private TextView shopTitleIcon;
	@ViewInject(R.id.shopFavorable)
	private TextView shopFavorable;
	@ViewInject(R.id.shopComment)
	private TextView shopComment;
	@ViewInject(R.id.last_comment)
	private TextView last_comment;
	@ViewInject(R.id.shopStar)
	private TextView shopStar;
	@ViewInject(R.id.directBuyTips)
	private TextView directBuyTips;
	@ViewInject(R.id.directBuyLayout)
	private LinearLayout directBuyLayout;
	@ViewInject(R.id.directBuyBtn)
	private Button directBuyBtn;
	@ViewInject(R.id.directPayTips)
	private TextView directPayTips;


	private BaseAdapter baseAdapter;
	private static Shop shop;
	private String distance;

	private ShopItemListObject directPayItem = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
								 Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_shop_detail, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle(getResources().getString(R.string.title_shop_detail));
		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setHomeActivity(false);

		listHeaderView = (LinearLayout) mBaseActivity.getLayoutInflater().from(mBaseActivity).inflate(R.layout.fragment_shop_detail_header, null);
		ViewUtils.inject(this, listHeaderView);

		listView.addHeaderView(listHeaderView);

		msgListRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				refreshDate();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				msgListRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
			}
		});
		msgListRefreshLayout.autoRefresh();

	}

	//刷新整个页面数据
	private void refreshDate() {
		initShopDetailData();
	}

	//获取商家详情
	private void initShopDetailData() {
		if (shop == null) return;
		distance=shop.getDistance();
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("shopId", shop.getId());
		paramMap.put("latitude", "0");
		paramMap.put("longitude", "0");

		paramMap.put("payType", "2");
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_SHOP_DETAIL, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESHING);
					}

					@Override
					public void onCancelled() {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.DONE);
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
						shop = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), Shop.class);
						initShopDetailView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}

	private void initShopDetailView() {

		if (shop == null) return;
		App.bitmapUtils.display(shopIcon, shop.getThumbnailUrl());
		List<String> urls = new ArrayList<String>();
		urls.add(shop.getThumbnailUrl());
		 final List<String> urlsImg = urls;
		shopIcon.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MyImagerDetailFragment.setUrls(urlsImg);
				CommUtil.openSingleFragmentActivity(mBaseActivity,MyImagerDetailFragment.class);
			}
		});
		shopTitle.setText(shop.getBusinessName());
		shopTitleIcon.setText(shop.getBusinessName());

		if(distance!=null){
		shopDistance.setText(CommUtil.formatDistance(distance));
		}
		shopAddress.setText(shop.getBusinessAddress());
		shopComment.setText((StringUtils.isNotEmpty(shop.getRankPeopleNumber())? shop.getRankPeopleNumber()+"人评价" : "暂无评价"));
		shopStar.setText(StringUtils.isEmpty(shop.getRank())? "0" : new BigDecimal(shop.getRank()).setScale(1, BigDecimal.ROUND_HALF_DOWN).toString());

		//决定是否显示直接购买
		if (shop.getItems() != null) {
			for (ShopItemListObject listItem : shop.getItems()) {
				if ("1".equalsIgnoreCase(listItem.getGoodsType())) {//有
					directPayItem = listItem;
				}
			}
			if (directPayItem != null) {
				shop.getItems().remove(directPayItem);
				directBuyTips.setVisibility(View.GONE);
				directBuyLayout.setVisibility(View.VISIBLE);
				directPayTips.setText(Html.fromHtml("APP买单，尊享<font color='#ff6700'>"+directPayItem.getDiscount()+"</font>折上折"));
			} else {
				directBuyTips.setVisibility(View.VISIBLE);
				directBuyLayout.setVisibility(View.GONE);
			}
		}

		//商品列表
		if (baseAdapter == null) {
			baseAdapter = new BaseAdapter() {
				@Override
				public int getCount() {
					if (shop.getItems() == null) {
						return 0;
					} else {
						return shop.getItems().size();
					}
				}

				@Override
				public Object getItem(int i) {
					return shop.getItems().get(i);
				}

				@Override
				public long getItemId(int i) {
					return i;
				}

				@Override
				public View getView(int i, View view, ViewGroup viewGroup) {
					if (view == null) {
						view = mBaseActivity.getLayoutInflater().from(mBaseActivity).inflate(R.layout.fragment_shop_detail_list_item, null);
					}
					((TextView) view.findViewById(R.id.listTitle)).setText(shop.getItems().get(i).getItemName());
					((TextView) view.findViewById(R.id.listSubTitle)).setText(shop.getItems().get(i).getSummary());
					((TextView) view.findViewById(R.id.currentPrice)).setText("￥" + shop.getItems().get(i).getNewPrice());
					((TextView) view.findViewById(R.id.oldPrice)).setText("￥" + shop.getItems().get(i).getOldPrice());
					((TextView) view.findViewById(R.id.oldPrice)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//删除线
					((TextView) view.findViewById(R.id.saledNumber)).setText("已售 " + shop.getItems().get(i).getSaledNumber());
					App.bitmapUtils.display((ImageView) view.findViewById(R.id.listIcon), shop.getItems().get(i).getThumbnailUrl());
					return view;
				}
			};
		}
		listView.setAdapter(baseAdapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				if (i == 0) return;
				shop.getItems().get(i - 1).setShop(shop);
				ShopItemDetailFragment.setShopItemListObject(shop.getItems().get(i - 1));
				CommUtil.openSingleFragmentActivity(mBaseActivity, ShopItemDetailFragment.class);
			}
		});
		baseAdapter.notifyDataSetChanged();
	}

	@OnClick(R.id.directBuyBtn)
	public void onDirectBuyBtnClick(View view) {
		if (directPayItem != null) {
			ShopItemDetailObject itemDetailObject = new ShopItemDetailObject();
			itemDetailObject.setItemName("消费增值");
			itemDetailObject.setItemId(directPayItem.getItemId());
			itemDetailObject.setItemType(directPayItem.getItemType());
			itemDetailObject.setPayType(directPayItem.getPayType());
			itemDetailObject.setSaledNumber(directPayItem.getSaledNumber());
			itemDetailObject.setThumbnailUrl(directPayItem.getThumbnailUrl());
			itemDetailObject.setGoodsType(directPayItem.getGoodsType());
			itemDetailObject.setDiscount(directPayItem.getDiscount());
			itemDetailObject.setShop(shop);
			OrderConfirmFragment.setShopItemDetailObject(itemDetailObject);
			CommUtil.openSingleFragmentActivity(mBaseActivity, OrderConfirmFragment.class);
		}
	}
	/**
	 * 打开电话
	 * @param view
	 */
	@OnClick(R.id.ico_phone)
	public void phoneNumberClick(View view) {
		AlertDialog.Builder builder= new AlertDialog.Builder(mBaseActivity);
		builder.setTitle("拨打电话").setMessage("请问您确定拨打"+shop.getPhone());
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				if (StringUtil.isNotEmpty(shop.getPhone())) {
					Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + shop.getPhone()));
					startActivity(intent);
				}
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();

	}

	/**
	 * 打开地图
	 * @param view
	 */
	@OnClick(R.id.ico_address)
	public void addressLayoutClick(View view) {
		if (StringUtil.isNotEmpty(shop.getLatitude()) && StringUtil.isNotEmpty(shop.getLongitude())) {
			MapFragment.setName(shop.getBusinessName());
			MapFragment.setLatitude(shop.getLatitude());
			MapFragment.setLongitude(shop.getLongitude());
			CommUtil.openSingleFragmentActivity(mBaseActivity, MapFragment.class);
		}
	}

	@OnClick(R.id.commentLayout)
	public void commentLayoutBtn(View view) {
		WeDeCommentFragment.setShopId(shop.getId());
		CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeCommentFragment.class);
	}

	/**
	 * 商家促销跳转页面
	 * @param view
	 */
	@OnClick(R.id.shopSalesLayout)
	public void shopSalesLayoutBtn(View view) {
		ShopSalesDescFragment.setShopSalesTxt(shop);
		CommUtil.openSingleFragmentActivity(mBaseActivity, ShopSalesDescFragment.class);
	}
	/**
	 * 图文详情跳转页面
	 * @param view
	 */
	@OnClick(R.id.shopDetailLayout)
	public void shopDetailLayoutBtn(View view) {
		ShopImageDescFragment.setFullTxt(shop);
		CommUtil.openSingleFragmentActivity(mBaseActivity, ShopImageDescFragment.class);
	}

	public static void setShop(Shop shop) {
		ShopDetailFragment.shop = shop;
	}

	/**
	 * @return the homeFragmentInstent
	 */
	public static ShopDetailFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
